package com.gearbox.platform.deadline.service;

import com.gearbox.core.configuration.MetricConfiguration;
import com.gearbox.core.metric.CustomMetric;
import com.gearbox.core.metric.Metric;
import com.gearbox.core.metric.MetricCalculator;
import com.gearbox.core.model.Job;
import com.gearbox.core.service.JobService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Component
@ConditionalOnProperty(name = "system.type", havingValue = "deadline")
public class DeadlineMetricCalculator implements MetricCalculator {
    private static final Logger LOG = LoggerFactory.getLogger(DeadlineMetricCalculator.class);

    @Autowired
    private JobService jobService;

    @Autowired
    private MetricConfiguration metricConfiguration;

    @Override
    public Metric calculateMetric() {
        List<Job> waitingJobs = jobService.listWaitingJobs();
        LOG.info("waiting jobs={}", waitingJobs);
        int workLoad = calculateWorkLoad(waitingJobs);
        return new CustomMetric(metricConfiguration.getName(), BigDecimal.valueOf(workLoad));
    }

    private int calculateWorkLoad(List<Job> jobs) {
        return jobs.stream().map(Job::getTaskCount).mapToInt(Integer::valueOf).sum();
    }
}
